// script.js
const { createApp } = Vue;

const App = {
  data() {
    return {
      categories: window.phoneticData.map(cat => ({
        ...cat,
        isExpanded: true
      })),
      selectedSymbol: null,
      isSidebarOpen: false,
      audioCache: new Map(),    // 音频缓存系统
      activeCategory: null,     // 当前激活的分类
      lastAudio: null           // 最后播放的音频对象
    }
  },
  methods: {
    // 切换分类展开状态
    toggleCategory(category) {
      if (this.activeCategory === category) {
        this.activeCategory = null;
      } else {
        this.activeCategory = category;
        this.$nextTick(() => {
          // 滚动到激活的分类
          const container = this.$refs.symbolScroll;
          const activeGroup = container.querySelector('.symbol-group.active');
          if (activeGroup) {
            activeGroup.scrollIntoView({ 
              behavior: 'smooth',
              block: 'nearest',
              inline: 'start'
            });
          }
        });
      }
    },

    // 选择音标核心逻辑
    selectSymbol(symbol) {
      // 更新选中音标
      this.selectedSymbol = symbol;
      
      // 立即播放音频
      this.playSymbolAudio(symbol);
      
      // 预加载相邻音标
      this.preloadNeighborSymbols(symbol);
      
      // 移动端自动关闭侧边栏
      if (window.innerWidth < 768) {
        this.isSidebarOpen = false;
      }
    },

    // 主播放按钮逻辑
    playAudio() {
      if (this.selectedSymbol) {
        this.playSymbolAudio(this.selectedSymbol);
      }
    },

    // 核心音频播放方法
    playSymbolAudio(symbol) {
      try {
        // 停止上一个音频
        if (this.lastAudio) {
          this.lastAudio.pause();
          this.lastAudio.currentTime = 0;
        }

        // 获取或创建音频对象
        if (!this.audioCache.has(symbol.id)) {
          const audio = new Audio(symbol.audio);
          audio.preload = 'auto';
          this.audioCache.set(symbol.id, audio);
        }

        const audio = this.audioCache.get(symbol.id);
        this.lastAudio = audio;

        // 播放处理
        const playPromise = audio.play();
        
        // 处理浏览器播放限制
        if (playPromise !== undefined) {
          playPromise.catch(error => {
            console.log('播放需要用户交互:', error);
            this.showPlayWarning();
          });
        }
        
        // 添加播放反馈
        this.addPlayFeedback(symbol);

      } catch (e) {
        console.error('音频播放失败:', e);
        this.showPlayWarning();
      }
    },

    // 显示播放提示
    showPlayWarning() {
      const warningEl = document.createElement('div');
      warningEl.className = 'play-warning';
      warningEl.textContent = '请先点击页面任意位置解除静音限制';
      document.body.appendChild(warningEl);
      
      setTimeout(() => {
        warningEl.remove();
      }, 2000);
    },

    // 添加视觉反馈
    addPlayFeedback(symbol) {
      // 清除旧状态
      document.querySelectorAll('.playing').forEach(el => {
        el.classList.remove('playing');
      });

      // 查找当前音标元素
      const targetEl = document.querySelector(`[data-symbol-id="${symbol.id}"]`);
      if (targetEl) {
        targetEl.classList.add('playing');
        setTimeout(() => targetEl.classList.remove('playing'), 500);
      }
    },

    // 智能预加载相邻音标
    preloadNeighborSymbols(currentSymbol) {
      const currentCategory = this.categories.find(
        cat => cat.symbols.includes(currentSymbol)
      );
      
      if (!currentCategory) return;

      const index = currentCategory.symbols.indexOf(currentSymbol);
      const neighbors = [
        currentCategory.symbols[index - 1],
        currentCategory.symbols[index + 1]
      ];

      neighbors.forEach(symbol => {
        if (symbol && !this.audioCache.has(symbol.id)) {
          this.preloadAudio(symbol);
        }
      });
    },

    // 基础预加载方法
    preloadAudio(symbol) {
      if (!this.audioCache.has(symbol.id)) {
        const audio = new Audio(symbol.audio);
        audio.load();
        this.audioCache.set(symbol.id, audio);
      }
    }
  },
  mounted() {
    // 初始化第一个音标
    if (this.categories.length > 0 && this.categories[0].symbols.length > 0) {
      const firstSymbol = this.categories[0].symbols[0];
      this.preloadAudio(firstSymbol);
      this.activeCategory = this.categories[0];
    }

    // 解除浏览器自动播放限制
    document.addEventListener('click', this.handleFirstInteraction);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleFirstInteraction);
  }
}

// 初始化Vue应用
createApp(App).mount('#app');